import {messages} from "share/common";
/**
 * Created by zhouli on 2019/2/27
 */
/*
* 需后端修改响应类型
* 不返回 JSON
* 改法：参考接口 http://192.168.10.31:8002/api/upload/attachment/v2, 目前已经上dev
* */
import React from 'react';
import config from 'config'
import Upload from 'rc-upload';
import {Icon, Button, message} from 'antd';

import 'styles/components/template/ie-file-upload/file-upload.scss'
import errorMessage from "share/errorMessage";
import httpFetch from "share/httpFetch";

const str2ab = (str) => {
  const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
  const bufView = new Uint16Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

class FileUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileName: "",
      loading: false,
    }
  }

  str2ab = (str) => {
    const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    const bufView = new Uint16Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }

  render() {
    const that = this;
    const uploaderProps = {
      action: this.props.uploadUrl,
      data: {
        access_token: this.props.token,
        ...that.props.data
      },
      //ie下不支持设置 header
      //https://github.com/react-component/upload/issues/22
      headers: {},
      multiple: true,
      disabled: that.props.disabled,
      accept: that.props.accept,
      responseType: 'arraybuffer',
      beforeUpload(file) {
        if (that.props.beforeUpload(file)) {
          that.setState({
            fileName: file.name
          });
          return true;
        } else {
          return false;
        }
      },
      customRequest: (option) => {
        const formData = new FormData();
        formData.set('accountPeriod', option.data.accountPeriod);
        formData.set('file', option.file)
        httpFetch.post(option.action, formData, {'Content-Type': 'multipart/form-data'}, {responseType: 'arraybuffer'}).then(res => {
          option.onSuccess(res)
        }).catch(err => {
          var errorData = JSON.parse(new TextDecoder("utf-8").decode(err.response.data));
          option.onError(errorData, errorData)
        })
      },
      onStart: (file) => {
        that.setState({
          loading: true,
        })
      },
      onSuccess(res) {
        that.setState({
          loading: false,
        });
        that.props.onChange(res);
      },
      onProgress(step, file) {
        that.setState({
          loading: true,
        });
        console.log('onProgress', Math.round(step.percent), file.name);
      },
      onError(err, note) {
        that.setState({
          loading: false,
        });
        if (note) {
          message.error(note.message || 'error');
        }
      },
    };
    const {fileName, loading} = this.state;
    return (
      <div className="file-upload-wrap">
        <div className="file-name">{fileName}</div>
        <Upload {...uploaderProps}>
          <Button disabled={this.props.disabled} loading={loading} className="file-upload-button">
            <Icon type="upload"/> {messages('components.key492')/*上传文件*/}
          </Button>
        </Upload>
      </div>
    );
  }
}

FileUpload.propTypes = {
  data: React.PropTypes.any,
  token: React.PropTypes.any,
  beforeUpload: React.PropTypes.func,//上传之前检测，返回false不上传
  uploadUrl: React.PropTypes.string,  //上传URL
  onChange: React.PropTypes.func,  //上传成功后的回调
  disabled: React.PropTypes.any,
};
FileUpload.defaultProps = {
  data: {},
  uploadUrl: `${config.baseUrl}/api/upload/attachment/v2`,
  beforeUpload: () => true,
  disabled: false,
};

export default FileUpload;

